package com.moblie.controller;



import com.alibaba.dubbo.config.annotation.Reference;
import com.moblie.constant.GitHubConstant;
import com.moblie.domain.User;
import com.moblie.entity.Result;
import com.moblie.service.UserService;
import com.moblie.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;


import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 卿通胜
 * @version 1.0
 * @date 2020/5/30 15:50
 */
@CrossOrigin(allowCredentials="true",allowedHeaders="*")
@RestController
@RequestMapping("/gitHubOauth")
public class GitHubOauthController {

   // 通过refrence注解得到userservice
   @Reference
   private UserService userService;

   //回调地址
   @RequestMapping("/callback")
   public Result callback(String code, String state, Model model, HttpServletRequest req) throws Exception {

      if (code != null && code.length() > 0 && state != null && state.length() > 0) {
         //拿到我们的code,去请求token
         //发送一个请求到
         String token_url = GitHubConstant.TOKEN_URL.replace("CLIENT_ID", GitHubConstant.CLIENT_ID)
                 .replace("CLIENT_SECRET", GitHubConstant.CLIENT_SECRET)
                 .replace("CALLBACK", GitHubConstant.CALLBACK)
                 .replace("CODE", code);
         System.out.println(token_url);
        //String token_url = GitHubConstant.TOKEN_URL.replace("CODE", code);
         //得到的responseStr是一个字符串需要将它解析放到map中
         String responseStr = HttpClientUtils.doGet(token_url);
         // 调用方法从map中获得返回的--》 令牌
         String token = HttpClientUtils.getMap(responseStr).get("access_token");

         //根据token发送请求获取登录人的信息  ，通过令牌去获得用户信息
         String userinfo_url = GitHubConstant.USER_INFO_URL.replace("TOKEN", token);
         responseStr = HttpClientUtils.doGet(userinfo_url);//json

         Map<String, String> responseMap = HttpClientUtils.getMapByJson(responseStr);
         // 获取responseMap中的id值,为该用户gitHubId值和用户名
         String gitHubId = responseMap.get("id");
         String username = responseMap.get("twitter_username");
         // 如果id值不为空,则调用userservice中的gitHubLogin方法,参数为给gitHubId的int类型值
         User user = new User();
         if (gitHubId.length()>0&gitHubId!=null){
            // 返回参数为user的信息
            user =  userService.gitHubLogin(Integer.parseInt(gitHubId),username);
         }

         // 授权成功返回认证成功信息,并携带user对象信息
         return new Result(true,"认证成功",user);
      }
      // 授权失败,否则提示授权失败
      return new Result(false,"授权失败");
   }


}
